package wjh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import wjh.mapper.RegisterMapper;
import wjh.pojo.*;
import wjh.service.RegisterService;
import wjh.utils.AlipayUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private RegisterMapper registerMapper;

    //从首页导航栏获取id查找医生
    @RequestMapping("/findDoctorById")
    public String findDoctorById(@RequestParam("id") Integer id, HttpSession session) {
        Doctor doctor = registerService.findDoctorById(id);
        session.setAttribute("doctor", doctor);
        return "redirect:/register/doctorFindAll.do";
    }

    //医生查询全部
    @RequestMapping("/doctorFindAll")
    public String doctorFindAll(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "3") Integer pageSize,
            @RequestParam(required = false) String user_name,
            @RequestParam(required = false) String records_number,
            HttpSession session,
            Model model) {
        Doctor doctor = (Doctor) session.getAttribute("doctor");
        int doctor_id = doctor != null ? doctor.getId() : 0;
        PageHelper.startPage(pageNum, pageSize);
        List<Register> registerList = registerService.doctorFindAll(doctor_id,user_name,records_number);
        model.addAttribute("doctor_id", doctor_id);
        PageInfo<Register> pageInfo = new PageInfo<>(registerList);
        model.addAttribute("page", pageInfo);
        model.addAttribute("user_name", user_name);
        model.addAttribute("records_number", records_number);
        return "doctorRegister";
    }

    //从首页导航栏获取id查找患者
    @RequestMapping("/findPatientById")
    public String findPatientById(@RequestParam("id") Integer id, HttpSession session) {
        Patient patient = registerService.findPatientById(id);
        session.setAttribute("patient", patient);
        return "redirect:/register/findAll.do";
    }

    //患者查询全部
    @RequestMapping("/findAll")
    public String findAll(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "3") Integer pageSize,
            @RequestParam(required = false) String records_number,
            HttpSession session, Model model) {
        Patient patient = (Patient) session.getAttribute("patient");
        int patientId = patient != null ? patient.getId() : 0;
        PageHelper.startPage(pageNum, pageSize);
        List<Register> registerList = registerService.findByNum(records_number,patientId);
        model.addAttribute("patientId", patientId);
        PageInfo<Register> pageInfo = new PageInfo<>(registerList);
        model.addAttribute("page", pageInfo);
        model.addAttribute("record_number", records_number);
        return "patientRegister";
    }




    //根据患者id查询信息
    @RequestMapping("/findByPatientId")
    public String findByPatientId(@RequestParam("patientId")String id,Model model){
        Patient patient = registerService.findPatientById(Integer.parseInt(id));
        model.addAttribute("patient",patient);
        return "addRegister";
    }

    @RequestMapping("/getFee")
    public ResponseEntity<Map<String, Object>> getFee(@RequestParam("doctorId") String doctorId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 查询挂号费
            int fee = registerService.getRegistrationFee(doctorId);
            response.put("fee", fee);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("error", "Unable to fetch registration fee.");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    //签到
    @PostMapping("/toSign")
    @ResponseBody
    public Map<String, Object> signIn(@RequestParam Integer id) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = registerService.signIn(id);
            if (result) {
                response.put("success", true);
                response.put("message", "签到成功");
            } else {
                response.put("success", false);
                // 根据业务逻辑决定具体的消息
                // 例如: "未到签到时间", "签到已过期", "记录不存在" 或 "已签到"
                response.put("message", determineSignInMessage(id));
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误");
        }
        return response;
    }

    //判断前端状态
    private String determineSignInMessage(Integer id) {
        Register record = registerMapper.findById(id);
        if (record == null) {
            return "记录不存在";
        }
        LocalDateTime now = LocalDateTime.now();
        java.util.Date utilDate = record.getDate();
        LocalDateTime recordDateTime = utilDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        LocalDateTime signInDeadline = recordDateTime.withHour(9).withMinute(0).withSecond(0);

        if (now.isBefore(signInDeadline)) {
            return "未到签到时间";
        } else if (now.isAfter(signInDeadline.plusHours(1))) {
            return "签到已过期";
        } else if ("已签到".equals(record.getStatus())) {
            return "已签到";
        } else {
            return "签到失败";
        }
    }




    //预约
    @RequestMapping("/addRegister")
    public String addRegister(Register register,Model model,Integer register_fee,HttpServletResponse response){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String records_number = now.format(formatter);
        register.setRecords_number(records_number);
        Integer doctorId=registerService.getDoctorIdByName(register.getDoctor_name());
        register.setDoctor_id(doctorId);
        registerService.addRegister(register);
       /* String dayOfWeek = now.getDayOfWeek().name(); // Converts to Enum name (e.g., MONDAY)

        // Update the plan table
        registerService.decrementPlanNumber(doctorId, dayOfWeek);*/
//        registerService.addRegisterFee(records_number,register_fee);
        return AlipayUtil.confirmPayment(records_number, String.valueOf(register_fee),"挂号费","挂号费",response);

    }
    @RequestMapping(value = "/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付成功, 进入同步通知接口...");
        Notice notice2 = AlipayUtil.checkSign2(request);
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (notice2.isSignVerified()) {
            // 修改订单状态，改为 支付成功
            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println(notice2);
            System.out.println("***************************************************************");
        } else {
            System.out.println("支付, 验签失败...");
        }
        return notice2.getModelAndView();
    }
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付成功, 进入异步通知接口...");
        Notice notice2 = AlipayUtil.checkSign2(request);
        //实际验证过程建议务必添加订单号、实际支付金额、商户操作、APPID校验：
        if (notice2.isSignVerified()) {//验证成功
            if (notice2.getTradeStatus().equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果有做过处理，不执行商户的业务程序
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (notice2.getTradeStatus().equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                System.out.println("********************** 支付成功(支付宝异步通知) **********************");
                System.out.println(notice2);
                System.out.println("***************************************************************");
            }
            System.out.println("支付成功...");
        } else {//验证失败
            System.out.println("支付, 验签失败...");
        }
        System.out.println("ssssssssssssssssssssssssssssssssssss");
        return "succ2";
    }

    //获取科室信息
    @RequestMapping("/getDepartments")
    public ResponseEntity<Map<String, Object>> getDepartments() {
        List<Department> department = registerService.findAllDepartments();
        Map<String, Object> response = new HashMap<>();
        response.put("department", department);
        return ResponseEntity.ok(response);
    }

    //根据 预约时间和科室 获取医生信息
    @RequestMapping("/getDoctors")
    public ResponseEntity<Map<String, Object>> getDoctors(@RequestParam String date, @RequestParam String id) {
            List<Doctor> doctor_name = registerService.findDoctorsByDateAndDepartment(date, id);
        Map<String, Object> response = new HashMap<>();
        response.put("doctor_name", doctor_name);
        return ResponseEntity.ok(response);
    }





    //查看病历
    @RequestMapping("/toThisRecord")
    public String toThisRecord(Model model, HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        Register record=registerService.findRecordsById(Integer.valueOf(id));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(record.getDate());
        model.addAttribute("formattedDate", formattedDate);
        model.addAttribute("record",record);
        return "showRecord";
    }

    //填写医嘱
    @RequestMapping("/toFillRecord")
    public String toFillRecord(Model model, HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        Register record=registerService.findRecordsById(Integer.valueOf(id));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(record.getDate());
        model.addAttribute("formattedDate", formattedDate);
        model.addAttribute("record",record);
        return "forward:/jsp/fillRecord.jsp";
    }

    //填写医嘱
    @PostMapping("/fillRecord")
    public ModelAndView fillRecord(@RequestParam String orders,@RequestParam int id, Model model){
        registerService.fillRecord(orders,id);
        model.addAttribute("record",orders);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/register/doctorFindAll.do");
        return modelAndView;
    }


    //删除病历
    @RequestMapping("/deleteRegister")
    public ResponseEntity<String> deleteRegisters(@RequestParam String ids) {
        try {
            registerService.deleteRegisters(ids);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            // 记录异常并返回错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
        }
    }


    //取消预约
    @RequestMapping("/toCancel")
    public ResponseEntity<String> toCancel(@RequestParam String id) {
        try {
            registerService.cancelRegisters(id);
            return ResponseEntity.ok("取消成功");
        } catch (Exception e) {
            // 记录异常并返回错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("取消失败");
        }
    }

}
